<template>
  <div class="login">
    <img src="../assets/logo.png" alt="">
    <el-form
      ref="ruleFormRef"
      :model="formInfo"
      :rules="rules"
      >
      <el-form-item prop="username">
        <el-input v-model="formInfo.username" prefix-icon="User">
        </el-input>
      </el-form-item>

      <el-form-item prop="password">
        <el-input v-model="formInfo.password" type="password" prefix-icon="Lock">
        </el-input>
      </el-form-item>

      <el-form-item label-width="150px">
        <el-button type="primary" :plain="true" @click="handleLogin">登录</el-button>
        <el-button type="info" @click="reset(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { login } from '@/api/login'
import { useStore } from 'vuex';
import { ElMessage } from 'element-plus'


const store = useStore()
const formInfo = ref({
  username: 'admin',
  password: '123456'
})

// 校验规则
const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' }
  ]
})

// 点击登录事件
const ruleFormRef = ref(null)

const handleLogin = () => {
  // 验证规则
  ruleFormRef.value.validate(async (valid) => {
    if (valid) {
      // 获取用户信息
      const res = await login(formInfo.value)

      // 判断登录状态
      if (res.data.meta.status === 200) {
        // 存储token值
        store.dispatch('login', res.data.data.token)
        ElMessage({
          showClose: true,
          message: res.data.meta.msg,
          type: 'success',
        })
      } else {
         ElMessage({
          showClose: true,
          message: res.data.meta.msg,
          type: 'error',
        })
      }

    } else {
      // console.log('error submit!')
      return false
    }
  })

}
// 重置信息
const reset = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
  // formInfo.value = ''
}


</script>

<style scoped lang='less'>
img{
  position: relative;
  left: 50%;
  width: 150px;
  border-radius: 50%;
  margin-left: -75px;
  margin-top: -100px;
  margin-bottom: 30px;
  box-shadow: 0,1px,10px,#ccc;
  border: 10px solid #fff;
  box-sizing: border-box;
  background-color: #eee;
}
.login{
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  width: 450px;
  height: 300px;
  background-color: #fff;
  border-radius: 3px;
  box-sizing: border-box;
}

</style>
